home *** CD-ROM | disk | FTP | other *** search
- /**************************************************************************/
- /* Calculate π by "shooting a cannon" at a round pond of radius 1 */
- /* 'inscribed' in a 2 x 2 square of land. */
- /* This is a variation of the "Monte Carlo" method of simulation */
- /* */
- /* Note| Center of circle is at (1,1). Corners of land are: */
- /* (0,0), (2,0), (2,2), (0,2). */
- /* */
- /* M\Cooper */
- /* 3425 Chestnut Ridge Rd. */
- /* Grantsville, MD 21536 */
- /* ------------------------- */
- /* email: thegrendel@aol.com */
- /* */
- /* 06/91 */
- /* Source code placed in the public domain */
- /**************************************************************************/
-
-
-
-
- #include <math.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <stdio.h>
-
- #define MAXSHOTS 50000
- #define MAXNUM 20000
- #define UPPER_LIMIT 2
-
- /**********************************************************************/
- /* GETRAND() */
- /* Outputs random number (0.0 - 2.0) */
- /**********************************************************************/
-
- double getrand()
-
- {
- double scale_factor, /*scaling factor*/
- rndnum,
- rand0_2; /*random number between 0.0 and 2.0 returned by fn*/
-
- scale_factor = (double)MAXNUM / (double)UPPER_LIMIT;
- rndnum = (double)random( MAXNUM );
-
- rand0_2 = rndnum / scale_factor;
-
- return( rand0_2 );
- }
-
- /**************************************************************************/
-
-
- void main()
- {
- double X,
- Y,
- Dx,
- Dy,
- distance,
- ratio,
- Pi;
- long shots = 0,
- splashes = 0,
- thuds = 0;
-
- randomize();
- clrscr();
-
-
- while( shots < MAXSHOTS )
- {
-
- shots++;
-
- X = getrand(); /*Generate X and Y coordinates*/
- Y = getrand(); /* of shots */
- /* Origin is at (1.0,1.0), remember */
-
- Dx = X - 1.0; /*find distance from origin*/
- Dy = Y - 1.0;
- distance = hypot( Dx,Dy ); /* by Pythagorean Theorem */
-
-
- if( distance <= 1.0 )
- {
- splashes++;
- printf("SPLASH! ");
- }
- else
- {
- thuds++;
- printf("THUD. ");
- }
-
- printf("%5ld splashes | %5ld thuds ", splashes, thuds);
-
- ratio = (double)splashes / (double)shots; /* Should be ≈ ¼π */
- Pi = ratio * 4.0;
-
- printf("At %5ld shots ---- π ≈ %2.8f\n", shots, Pi);
-
- }
-
-
- }
-